//
//  HESystemInfoViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/12/23.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HESystemInfoViewController.h"
#import "HESysMsgCell.h"
#import "HESysMsgModel.h"
#import "HEOrderDetailsViewController.h"
#import "HEActiveCell.h"
#import "HEActiveDetailsViewController.h"
#import "HEProxyPayCell.h"
@interface HESystemInfoViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, strong) NSMutableArray * dataSourceArr;
@property (nonatomic, strong) NSMutableArray *sections;

@end

@implementation HESystemInfoViewController

- (NSMutableArray *)dataSourceArr {
    if (!_dataSourceArr) {
        _dataSourceArr = [NSMutableArray array];
    }
    return _dataSourceArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _pageNum = 1;
    _pageSize = 10;
    
    self.title = @"系统消息";
    
    [self setCustomTableView:self.tableView];
    [self showEmpty];
    [self.view addSubview:self.tableView];
 
    self.view.backgroundColor = CLightGrayColor;
  
    [self loadData];
}

- (NSMutableArray <GDFiterCellModel *>*)sections {
    if (!_sections) {
        _sections = @[].mutableCopy;
    }
    return _sections;
}

#pragma mark -
- (GDTableView *)tableView {
   if (!_tableView) {
       _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight, KScreenWidth, KScreenHeight - (ZXNavBarHeight)) style:UITableViewStyleGrouped];
       _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
       _tableView.scrollsToTop = YES;
       _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];
       _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];

       _tableView.showsVerticalScrollIndicator = NO;
       _tableView.backgroundColor = CViewBgColor;
       _tableView.delegate = self;
       _tableView.dataSource = self;

       __weak __typeof(&*self)weakSelf = self;
       self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{

           weakSelf.isFromHeadRefresh = YES;
           weakSelf.pageNum = 1;
           [weakSelf loadData];
       }];

       self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
           weakSelf.isFromHeadRefresh = NO;
           weakSelf.pageNum += 1;
           [weakSelf loadData];
       }];
       
       [_tableView registerClass:HESysMsgCell.class forCellReuseIdentifier:@"HESysMsgCell"];
       [_tableView registerClass:HEActiveCell.class forCellReuseIdentifier:@"HEActiveCell"];
       [_tableView registerClass:HEProxyPayCell.class forCellReuseIdentifier:@"HEProxyPayCell"];
   }
   return _tableView;
}
 

#pragma mark - loadData
- (void)loadData {
    HEPageRequest *req = [HEPageRequest new];
    req.pageNum = _pageNum;
    req.pageSize = _pageSize;
    
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KSyslist parameters:req success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);
        HEPageResponse *response = [HEPageResponse mj_objectWithKeyValues:responseObject];
 
        if (self.isFromHeadRefresh) {
            [self.dataSourceArr removeAllObjects];
            [self.sections removeAllObjects];
        }
        
        NSArray *arr = [HESysMsgModel mj_objectArrayWithKeyValuesArray: response.data.list];
        [self dealData: arr];
        
        [self.tableView reloadData];

        if (self.dataSourceArr.count == 0) {
            [self showEmpty];
        }else {
            if (response.data.list.count == 0) {
                [Dialog toastBottom:@"没有更多数据了~"];
            }
        }
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    } failure:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}

// 分配cell类型
- (void)dealData:(NSArray *)arr {
    for (HESysMsgModel *info in arr) {
        NSObject *item = nil;
        GDFiterCellModel *fiterModel = [GDFiterCellModel new];
        
        if (info.sysType == HESysInfoTypeACTIVITY) {
            item = (HEActiveModel *)info.params;
            fiterModel.cellKlass = HEActiveCell.class;
        }else if (info.sysType == HESysInfoTypeProxyPay) {
            item = info;
            fiterModel.cellKlass = HEProxyPayCell.class;
        }else {
            item = info;
            fiterModel.cellKlass = HESysMsgCell.class;
        }
        
        [self.dataSourceArr addObject: item];
        [self.sections addObject: fiterModel];
    }
}

 
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _sections.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GDFiterCellModel *fiterModel = _sections[indexPath.row];
    MCTableBaseCell *cell = (MCTableBaseCell *)[_tableView dequeueReusableCellWithIdentifier: fiterModel.cellId];
    [cell configCellWithModel: _dataSourceArr[indexPath.row]];
   return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    GDFiterCellModel *fiterModel = _sections[indexPath.row];
    return [tableView fd_heightForCellWithIdentifier: fiterModel.cellId cacheByIndexPath:indexPath configuration:^(MCTableBaseCell *cell) {
        [cell configCellWithModel: self.dataSourceArr[indexPath.row]];
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSObject *obj = self.dataSourceArr[indexPath.row];
    
    if ([HESysMsgModel.class isEqual: obj.class]) {
        HESysMsgModel *msg = (HESysMsgModel *)obj;
        [self markSysRead: msg];
        
        switch (msg.sysType) {
            case HESysInfoTypeADD_NUM:
            {
                HEOrderModel *order = (HEOrderModel *)msg.params;
                HEOrderDetailsViewController *vc = [HEOrderDetailsViewController new];
                vc.orderId = order.orderItemList.firstObject.orderId;
                [self.navigationController pushViewController:vc animated:YES];
            }
                break;
            case HESysInfoTypeProxyPay:
            {
                HEProxyPayInfoModel *order = (HEProxyPayInfoModel *)msg.params;
                HEOrderDetailsViewController *vc = [HEOrderDetailsViewController new];
                vc.orderId = order.order_id;
                [self.navigationController pushViewController:vc animated:YES];
            }
                break;
                
            default:
                break;
        }
    }
    else {
        [self markActiveRead: (HEActiveModel *)obj];
        HEActiveDetailsViewController *vc = [HEActiveDetailsViewController new];
        vc.activeId = ((HEActiveModel *)obj).id;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

// 标记活动已读
- (void)markActiveRead:(HEActiveModel *)msg {
    if(!msg.showRead) {
        return;
    }
    [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:Kreadmsg parameters:@{@"id" : [NSNumber numberWithInteger: msg.msg_id]} success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            msg.showRead = NO;
            [self.tableView reloadData];
        }
    } failure:^(NSError * _Nonnull error) {
    }];
}

/// 标记系统已读
- (void)markSysRead:(HESysMsgModel *)msg {
    if(msg.is_read) {
        return;
    }
    [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:Kreadmsg parameters:@{@"id" : [NSNumber numberWithInteger: msg.id]} success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            msg. is_read = YES;
            [self.tableView reloadData];
        }
    } failure:^(NSError * _Nonnull error) {
    }];
}

#pragma mark -
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *v = [UIView new];
    v.backgroundColor = CLightGrayColor;
    return v;
}

@end
